const coefficient = 0.05;

module two {
	export class MapPage extends BaseComponent {
		private _camObj: paper.GameObject;
		private _cam: egret3d.Camera;
		private _light: paper.GameObject;

		public touchLayer: eui.Group;
		private _config: IStarConfig[] = [];
		private _ballList = [];

		public btn_list: eui.Button;

		public btn_star: eui.Button;
		public orientationBtn: eui.Button;
		public handBtn: eui.Button;

		public flag_choose: eui.Image;

		public gp_op: eui.Group;
		public gp_list: eui.Group;
		public list_stars: eui.List;
		public btn_close: eui.Button;
		public btn_scan: eui.Button;

		public soundCloseBtn: eui.Button;
		public soundOpenBtn: eui.Button;


		public label1: eui.Label;
		public label2: eui.Label;

		public isOrientation: boolean = false;

		private _moveTouchEvent = {
			startPointX: 0,
			startPointY: 0,
			currentPointX: 0,
			currentPointY: 0,
			fingerId: 0,
		}
		private _moveOrientationEvent = {
			lastX: 0,
			lastY: 0,
			currentX: 0,
			currentY: 0,
		}
		public constructor() {
			super("MapPage");
		}

		protected removed(): void {
			super.removed();

			egret.Tween.removeTweens(this.flag_choose);
			one.monitor.off("onHideJewelry", this.onHideJewelry, this);

			one.monitor.off("onTouchBallMapPage", this.onTouchBall, this);
			one.monitor.off("onShowJewelry", this.onShowJewelry, this);

			let _camObj = paper.GameObject.find("Main Camera");
			_camObj.activeSelf = false;

			if (MapPage.orienter) {
				MapPage.orienter.off();
			}
		}

		protected created(): void {
			super.created();
			let _camObj = paper.GameObject.find("Main Camera");
			_camObj.activeSelf = true;

			this.initSelectState();
			this.flag_choose.width = 90;
			this.flag_choose.height = 90;
			egret.Tween.get(this.flag_choose, { loop: true }).to({
				width: 120,
				height: 120
			}, 1000).to({
				width: 90,
				height: 90
			}, 1000)
			two.addTap(this.btn_star, () => {
				showJewPage(this.chooseStarId);
			})


			two.addTap(this.soundOpenBtn, () => {
				this.soundOpenBtn.visible = false;
				this.soundCloseBtn.visible = true;

				this.openSound(false);
			})
			two.addTap(this.soundCloseBtn, () => {
				this.soundOpenBtn.visible = true;
				this.soundCloseBtn.visible = false;

				this.openSound(true);
			})
			this.soundOpenBtn.visible = true;
			this.soundCloseBtn.visible = false;

			two.addTap(this.orientationBtn, () => {
				this.isOrientation = true;
				this.orientationBtn.visible = false;
				this.handBtn.visible = !this.orientationBtn.visible;
				this.initSelectState();

				this._moveOrientationEvent.currentX = 0;
				this._moveOrientationEvent.currentY = 0;
			})

			this.touchLayer.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.touchBegin, this);
			this.touchLayer.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.touchMove, this);
			this.touchLayer.addEventListener(egret.TouchEvent.TOUCH_END, this.touchEnd, this);
			this.touchLayer.addEventListener(egret.TouchEvent.TOUCH_CANCEL, this.touchEnd, this);

			//白天黑夜
			let _now = new Date().getHours();
			let _box = paper.GameObject.find("star");
			if (_now >= 6 && _now <= 17) {
				RES.getResAsync("Assets/star/starbg_day.jpg", (texture: egret3d.BaseTexture) => {
					_box.getComponentsInChildren(egret3d.MeshRenderer)[0].material.setTexture(texture);
				}, this);
			}
			else {
				RES.getResAsync("Assets/star/starbg_night.jpg", (texture: egret3d.BaseTexture) => {
					_box.getComponentsInChildren(egret3d.MeshRenderer)[0].material.setTexture(texture);
				}, this);
			}

			this.gp_op.visible = true;
			this.gp_list.visible = false;
			two.addTap(this.btn_list, () => {
				this.gp_op.visible = false;
				this.gp_list.visible = true;
				this.isOrientation = false;
				this.orientationBtn.visible = true;
				this.handBtn.visible = !this.orientationBtn.visible;
				this.initStarList();
			});
			two.addTap(this.btn_close, () => {
				this.gp_op.visible = true;
				this.gp_list.visible = false;
			});
			two.addTap(this.btn_scan, () => {
				two.scan();
			});

			one.monitor.on("onHideJewelry", this.onHideJewelry, this);

			one.monitor.on("onTouchBallMapPage", this.onTouchBall, this);
			one.monitor.on("onShowJewelry", this.onShowJewelry, this);

			this._camObj = paper.GameObject.find("Main Camera");
			if (!this._camObj.getComponent(CameraControl)) {
				this._camObj.addComponent(CameraControl);
			}
			this._cam = this._camObj ? this._camObj.getComponent(egret3d.Camera) : egret3d.Camera.main;

			if (this._config.length <= 0) {
				this.initBall();
			}

			this.onRotationHandler();

			if (MapPage.IS_FIRST) {
				MapPage.IS_FIRST = false;
				this.checkOpen();
			}

			this.isOrientation = true;
			this.orientationBtn.visible = false;
			this.handBtn.visible = !this.orientationBtn.visible;
			this.initSelectState();

			this._moveOrientationEvent.currentX = 0;
			this._moveOrientationEvent.currentY = 0;
		}

		private openSound(isOpen: boolean) {
			this.soundOpenBtn.enabled = false;
			this.soundCloseBtn.enabled = false;

			two.openSound(isOpen, () => {
				this.soundOpenBtn.enabled = true;
				this.soundCloseBtn.enabled = true;
			})
		}

		private static IS_FIRST: boolean = true;

		private initStarList(): void {
			let list = StarConfig.getAllConfigs();
			let ac = this.list_stars.dataProvider as eui.ArrayCollection;
			ac.removeAll();

			for (let i = 0; i < list.length; i++) {
				ac.addItem(list[i]);
			}
		}

		private chooseStarId: string = "";
		private onShowJewelry(data: { id: string }): void {
			for (let key in this._config) {
				if (this._config[key].id == data.id) {
					this.startMoveCam(paper.GameObject.find(this._config[key].name), this._config[key].id);
					break;
				}
			}
			this.gp_list.visible = false;
			this.gp_op.visible = true;

			this.isOrientation = false;
			this.orientationBtn.visible = true;
			this.handBtn.visible = !this.orientationBtn.visible;

			this.chooseStarId = data.id;
			this.btn_star.visible = true;
			this.flag_choose.visible = true;
			this.btn_star.label = StarConfig.getConfigById(data.id).name;

		}

		//返回星球页面
		private onHideJewelry(data: { id: string }): void {
			for (let key in this._config) {
				if (this._config[key].id == data.id) {
					let _obj = paper.GameObject.find(this._config[key].name);
					if (_obj) {
						this.startMoveCam(_obj, "", egret3d.Vector3.ZERO);
					}
				}
			}

			this.btn_star.visible = false;
			this.flag_choose.visible = false;
			this.chooseStarId = "";
		}

		async initBall() {
			// this._light = paper.GameObject.find("light");
			// this._light.activeSelf = true;
			// this._camObj.getComponent(CameraControl).light = this._light;
			// this._light.transform.position = this._camObj.transform.position;
			// this._light.transform.rotation = this._camObj.transform.rotation;

			// paper.GameObject.find("Directional Light (1)").activeSelf = false;
			this._ballList = [];
			await RES.getResAsync("config/stars.json");
			this._config = RES.getRes("config/stars.json");
			let _configArray = [];
			for (let key1 in StarsPossConfig.getAllConfigs()) {
				let _nameStar = StarsPossConfig.getAllConfigs()[key1][0].toString();

				let sk = "";
				for (let key2 in this._config) {
					if (_nameStar == this._config[key2].key) {
						sk = key2;
						break;
					}
				}

				let lat = StarsPossConfig.getAllConfigs()[key1][2] as number;
				let long = StarsPossConfig.getAllConfigs()[key1][1] as number;
				if (sk != "") {
					this._config[sk].x = 10 * Math.cos(lat) * Math.cos(long)
					this._config[sk].y = 10 * Math.cos(lat) * Math.sin(long)
					this._config[sk].z = 10 * Math.sin(lat)
					this._config[sk].isTouch = true;
				}
				else {
					_configArray.push({
						"id": _nameStar,
						"key": _nameStar,
						"name": _nameStar,
						"title": "",
						"x": 10 * Math.cos(lat) * Math.cos(long),
						"y": 10 * Math.cos(lat) * Math.sin(long),
						"z": 10 * Math.sin(lat),
						"isTouch": false,
						"icon": 1,
						"size": StarsPossConfig.getAllConfigs()[key1][4]
					});
				}
			}

			this._config = this._config.concat(_configArray);
			this._config.sort((a, b) => {
				return a.size - b.size;
			})
			console.log(this._config);
			for (let key in this._config) {
				let _obj = paper.GameObject.find(this._config[key].name);
				if (!_obj || _obj.isDestroyed) {
					// _obj = egret3d.DefaultMeshes.createObject(egret3d.DefaultMeshes.SPHERE);
					_obj = paper.GameObject.create();
					let _posconfig = StarsPossConfig.getConfigById(this._config[key].key);
					let lat = _posconfig[2] as number;
					let long = _posconfig[1] as number;
					_obj.transform.setPosition(this._config[key].x, this._config[key].y, this._config[key].z);
					// _obj.transform.setLocalScale(new egret3d.Vector3(0.6, 0.6, 0.6));
					_obj.name = this._config[key].name;
					// _obj.addComponent(egret3d.SphereCollider);
					_obj.addComponent(BallControl);
				}
				let _ballControl = _obj.getComponent(BallControl);
				_ballControl._cam = this._cam;
				let _item = new BallItem(this._config[key]);
				_item.anchorOffsetX = _item.width / 2;
				_item.anchorOffsetY = _item.height / 2;
				//min:-1.4  max:6.4
				if (this._config[key].hasOwnProperty("size")) {
					_item.scaleX = _item.scaleY = 0.2 + (this._config[key].size + 1.4) * 0.8 / 7.8;
				}
				this.touchLayer.addChild(_item);
				_ballControl.starNode = _item;
				this._ballList.push(_obj);
			}
		}

		startMoveCam(lookObj: paper.GameObject, selectId: string, endPos?: egret3d.Vector3) {
			this.initSelectState();

			this._camObj.transform.lookRotation(lookObj.transform.position);
			// this._camObj.getComponent(CameraControl).posStart = this._camObj.transform.position.clone();
			GameUtils.setTimeout(() => {
				if (endPos) {
					this._camObj.getComponent(CameraControl).posEnd = endPos.clone();
				}
				else {
					this._camObj.getComponent(CameraControl).posEnd = this._camObj.transform.getForward().normalize().clone().multiplyScalar(3)
				}
				this._camObj.getComponent(CameraControl).posEnd = this._camObj.getComponent(CameraControl).posStart;
				this._camObj.getComponent(CameraControl).selectId = selectId;
				this._camObj.getComponent(CameraControl).isOver = false;
			}, this, 50);
		}

		touchBegin(event: egret.TouchEvent) {
			if (!event.target || event.target.name != "touchLayer") {
				return;
			}
			if (event.target.name == "touchLayer") {
				this._moveTouchEvent.startPointX = event.stageX;
				this._moveTouchEvent.startPointY = event.stageY;
				this._moveTouchEvent.currentPointX = event.stageX;
				this._moveTouchEvent.currentPointY = event.stageY;
				this._moveTouchEvent.fingerId = event.touchPointID;
			}
		}

		touchMove(event: egret.TouchEvent) {
			if (this._moveTouchEvent.fingerId != 0 && event.touchPointID == this._moveTouchEvent.fingerId) {
				if (!this._camObj || this._camObj.isDestroyed) {
					return;
				}
				//屏幕移动处理
				this.isOrientation = false;
				this.orientationBtn.visible = true;
				this.handBtn.visible = !this.orientationBtn.visible;
				this.initSelectState();

				let deltaX = event.stageX - this._moveTouchEvent.currentPointX;
				let deltaY = event.stageY - this._moveTouchEvent.currentPointY;
				this._camObj.transform.rotate(0, coefficient * deltaX * Math.PI / 180, 0);
				this._camObj.transform.rotate(coefficient * -deltaY * Math.PI / 180, 0, 0);
				this._moveTouchEvent.currentPointX = event.stageX;
				this._moveTouchEvent.currentPointY = event.stageY;
			}
		}

		touchEnd(event: egret.TouchEvent) {
			if (this._moveTouchEvent.fingerId != 0 && event.touchPointID == this._moveTouchEvent.fingerId) {
				//屏幕移动结束
				this._moveTouchEvent.startPointX = 0;
				this._moveTouchEvent.startPointY = 0;
				this._moveTouchEvent.currentPointX = 0;
				this._moveTouchEvent.currentPointY = 0;
				this._moveTouchEvent.fingerId = 0;

				// let ray = this._cam.stageToRay(event.stageX, event.stageY);
				// for (let key in this._ballList) {
				// 	if (CollideUtils.raycast(ray, this._ballList[key])) {
				// 		this.startMoveCam(this._ballList[key], this._config[key].id);
				// 		console.log("点击了:" + this._ballList[key].name)
				// 	}
				// }
			}
		}

		onTouchBall(id: string) {
			showJewPage(id);
		}

		private static orienter: Orienter;
		onRotationHandler() {
			let that = this;

			if (MapPage.orienter == null) {
				MapPage.orienter = new Orienter();
			}
			MapPage.orienter.onOrient = function (obj) {
				if (!that.isOrientation) {
					//不是陀螺仪
					return;
				}

				let deltaX = obj.lon - that._moveOrientationEvent.currentX;
				let deltaY = obj.lat - that._moveOrientationEvent.currentY;

				if (Math.abs(deltaX) > 300) {
					deltaX = 0;
				}
				that._camObj.transform.rotate(0, -deltaX * Math.PI / 360, 0);
				that._camObj.transform.rotate(deltaY * Math.PI / 360, 0, 0);

				that.label1.text = obj.lon;
				that.label2.text = obj.lat;
				// that._camObj.transform.setEulerAngles(obj.lat,obj.lon,0);
				// that._camObj.transform.rotateOnAxis(egret3d.Vector3.LEFT, deltaY * Math.PI / 360);


				that._moveOrientationEvent.currentX = obj.lon;
				that._moveOrientationEvent.currentY = obj.lat;
			};
			MapPage.orienter.on();
		}

		initSelectState() {
			this.btn_star.visible = false;
			this.flag_choose.visible = false;
		}

		private checkOpen(): void {

			if (getOpenCode()) {
				let box = new LockConfirmBox();
				box.once("onOK", () => {
					two.checkCode(getOpenCode());
				}, null);
				two.showBox(box, 0, true);
			}

		}
	}

	two.setClassMap("map", "two.MapPage");
}